package com.changfeng.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.changfeng.auth.dto.UserAuth;
import com.changfeng.bean.dto.bo.MenuTopBO;
import com.changfeng.bean.dto.vo.MenuTopVO;
import com.changfeng.bean.dto.vo.MenuVO;
import com.changfeng.common.CurrentUser;
import com.changfeng.dao.ReatailersMenuMapper;
import com.changfeng.exception.ChangFengException;
import com.changfeng.exception.ChangFengExceptionEnum;
import com.changfeng.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private ReatailersMenuMapper reatailersMenuMapper;

    @Override
    public List<MenuTopVO> findByPowerId() {
        UserAuth userAuth = CurrentUser.getCurrentUser();
        List<MenuTopBO> topBOS = null;
        if (userAuth == null || userAuth.getPowerId() == null) {
            throw new ChangFengException(ChangFengExceptionEnum.ERROR);
        }
        if (userAuth.getPowerId() == 0) {
            topBOS = reatailersMenuMapper.findAll();
        } else {
            topBOS = reatailersMenuMapper.findByPowerId(userAuth.getPowerId());
        }

        if (topBOS == null) {
            throw new ChangFengException(ChangFengExceptionEnum.ERROR);
        }

        List<MenuTopVO> topVOS = new ArrayList<>();
        for (MenuTopBO bo : topBOS) {
            MenuTopVO vo = new MenuTopVO();
            vo.setMenuName(bo.getMenuName());
            vo.setMenuList(JSONObject.parseArray(bo.getMenuList(),MenuVO.class));
            topVOS.add(vo);
        }
        return topVOS;
    }
}
